<template>
  <div class="home">
    <div style="padding: 10px;">
      应用ID：{{ appId }}
      <a-divider type="vertical" />

      登陆账号：<span @click="showSign" style="cursor: pointer;">{{ userName }}</span>
      <a-divider type="vertical" />

      连接状态：
      <a-tag color="#87d068" v-if="state">成功</a-tag>
      <a-tag color="#f50" v-else>失败</a-tag>

      <a-divider type="vertical" />
      <a-button type="primary" size="small" @click="showGroupManager">群组管理</a-button>
      <a-divider type="vertical" />
      <a-button type="primary" size="small" @click="showGroupCreate">创建群组</a-button>
      <a-divider type="vertical" />
      <a-button type="primary" size="small" @click="showGroupJoin">加入群组</a-button>
      <a-divider type="vertical" />
      <a-button type="primary" size="small" @click="clearMessage">清空消息</a-button>
    </div>

    <div>
      <a-alert v-for="(item, index) in messages" type="info" :message="item.id" :description="item.text" :key="index" style="margin: 10px;"/>
    </div>

    <a-modal title="群组管理" :visible="visibleGroupManager" @ok="hideGroupManager" @cancel="hideGroupManager" okText="确定" cancelText="取消">
      <a-list itemLayout="horizontal"
              style="max-height: 300px; overflow-y: scroll"
              :infinite-scroll-disabled="busy"
              :infinite-scroll-distance="10"
              :dataSource="groups"
              :locale="{emptyText: '暂无群组'}">
        <a-list-item slot="renderItem" slot-scope="item">
          <a-list-item-meta>
            <a slot="title">{{ item.GroupId }}</a>
            <p slot="description" style="width: 400px;">{{ item.Type }} - {{ item.Name }}</p>
          </a-list-item-meta>

          <a-popconfirm v-if="item.Owner_Account === userName" title="是否解散群组？" @confirm="destroyGroup(item)" okText="是" cancelText="否">
            <a style="margin-right: 10px;">解散</a>
          </a-popconfirm>

          <a-popconfirm v-else title="是否退出群组？" @confirm="quitGroup(item)" okText="是" cancelText="否">
            <a style="margin-right: 10px;">退出</a>
          </a-popconfirm>
        </a-list-item>
      </a-list>
    </a-modal>

    <a-modal title="创建群组" :visible="visibleGroupCreate" @ok="createGroup" @cancel="hideGroupCreate" okText="确定" cancelText="取消">
        <a-select defaultValue="Public" style="width: 150px; margin-right: 10px;" @change="changeRoomType">
          <a-select-option value="Public">公开群</a-select-option>
          <a-select-option value="Private">私有群</a-select-option>
          <a-select-option value="ChatRoom">聊天室</a-select-option>
          <a-select-option value="AVChatRoom">互动直播聊天室</a-select-option>
        </a-select>
        <a-input v-model="createGroupForm.name" placeholder="请输入群组名称" style="width: 300px;"/>
    </a-modal>

    <a-modal title="加入群组" :visible="visibleGroupJoin" @ok="joinGroup" @cancel="hideGroupJoin" okText="确定" cancelText="取消">
        <a-input v-model="joinGroupForm.groupId" placeholder="请输入群组ID"/>
    </a-modal>
  </div>
</template>

<script>
  import webim from 'webim-tencent';

  export default {
    name: 'home',
    data() {
        return {
            appId: '',
            userName: '',
            sign: '',
            state: false,
            messages: [],
            groupCount: 100,
            groups: [],
            busy: false,
            visibleGroupManager: false,
            visibleGroupCreate: false,
            visibleGroupJoin: false,
            createGroupForm: {
                name: '',
                type: 'Public',
            },
            joinGroupForm: {
                groupId: '',
            },
        };
    },
    created() {
        console.log('home created');
        this.$http.get('/login').then((res) => {
            console.log('login', res);
            this.login(res);
        }).catch((err) => {
            console.error('login', err);
            this.$router.push({path: '/'});
        });
    },
    mounted() {
        console.log('home mounted');
    },
    methods: {
        showGroupManager() {
            this.visibleGroupManager = true;
        },
        hideGroupManager() {
            this.visibleGroupManager = false;
        },
        showGroupCreate() {
            this.visibleGroupCreate = true;
        },
        hideGroupCreate() {
            this.visibleGroupCreate = false;
        },
        showGroupJoin() {
            this.visibleGroupJoin = true;
        },
        hideGroupJoin() {
            this.visibleGroupJoin = false;
        },
        changeRoomType(value) {
            this.createGroupForm.type = value;
        },
        clearMessage() {
            this.messages = [];
            this.$message.success('清除成功');
        },
        showSign() {
            this.$success({
                title: '签名',
                content: this.sign,
            });
        },
        login(res) {
            this.appId    = res.data.sdkAppID;
            this.userName = res.data.identifier;
            this.sign     = res.data.userSig;

            let loginInfo = {
                'sdkAppID':     res.data.sdkAppID,
                'identifier':   res.data.identifier,
                'accountType':  res.data.accountType,
                'userSig':      res.data.userSig,
            };

            let listeners = {
                "onConnNotify": this.onConnNotify,
                "onMsgNotify": this.onMsgNotify,
            };

            webim.login(loginInfo, listeners);
        },

        // 加载群组
        initGroup() {
            if (!this.state) {
                this.$message.error('未登陆成功');
                return;
            }

            let _this = this;
            webim.getJoinedGroupListHigh({
                    'Member_Account': this.userName,
                    'Limit': this.groupCount,
                    'Offset': 0,
                    'GroupBaseInfoFilter': ['Type', 'Name', 'Owner_Account']
                },
                function (res) {
                    console.log('initGroup', res);
                    if (res.GroupIdList && res.GroupIdList.length > 0) {
                        _this.groups = [...res.GroupIdList];
                    }
                },
                function (err) {
                    console.error('initGroup', err);
                }
            );
        },

        // 创建群组
        createGroup() {
            if (!this.state) {
                this.$message.error('未登陆成功');
                return;
            }

            if (!this.createGroupForm.name) {
                this.$message.warning('请输入群组名称！');
                return;
            }

            let _this = this;
            webim.createGroup({
                    'Name': _this.createGroupForm.name,
                    'Type': _this.createGroupForm.type,
                    'Owner_Account': _this.userName,
                    'MemberList': [_this.userName],
                },
                function (res) {
                    console.log('createGroup', res);
                    if (res.ActionStatus === 'OK') {
                        _this.$message.success('创建成功');
                        _this.hideGroupCreate();
                        _this.initGroup();
                    } else {
                        _this.$message.error('创建失败');
                    }
                },
                function (err) {
                    console.error('createGroup', err);
                    _this.$message.error('创建失败');
                }
            );
        },

        // 加入群组
        joinGroup() {
            if (!this.state) {
                this.$message.error('未登陆成功');
                return;
            }

            if (!this.joinGroupForm.groupId) {
                this.$message.warning('请输入群组ID！');
                return;
            }

            let _this = this;
            webim.applyJoinGroup({
                    'GroupId': _this.joinGroupForm.groupId,
                    'ApplyMsg': 'join',
                    'UserDefinedField': ''
                },
                function (res) {
                    console.error('joinGroup', res);
                    if (res.ActionStatus === 'OK') {
                        _this.$message.success('加入成功');
                        _this.hideGroupJoin();
                        _this.initGroup();
                    } else {
                        _this.$message.error('加入失败');
                    }
                },
                function (err) {
                    console.error('joinGroup', err);
                    _this.$message.error('加入失败');
                }
            );
        },

        // 退出群组
        quitGroup(item) {
            const groups = [...this.groups];
            let _this = this;
            webim.quitGroup({GroupId: item.GroupId},
                function (res) {
                    console.log('quitGroup', res);
                    _this.groups = groups.filter(i => i.GroupId !== item.GroupId);
                    _this.$message.success('退出成功');
                },
                function (err) {
                    console.error('quitGroup', err);
                    _this.$message.error('退出失败');
                }
            );
        },

        // 解散群组
        destroyGroup(item) {
            const groups = [...this.groups];
            let _this = this;
            webim.destroyGroup({GroupId: item.GroupId},
                function (res) {
                    console.log('destroyGroup', res);
                    _this.groups = groups.filter(i => i.GroupId !== item.GroupId);
                    _this.$message.success('解散成功');
                },
                function (err) {
                    console.error('destroyGroup', err);
                    _this.$message.error('解散失败');
                }
            );
        },

        // 监听链接状态事件
        onConnNotify(res) {
            switch (res.ErrorCode) {
                case webim.CONNECTION_STATUS.ON:
                    this.state = true;
                    console.log('connect', res.ErrorInfo);
                    this.$http.get('/success');
                    this.initGroup();
                    break;
                case webim.CONNECTION_STATUS.OFF:
                    this.state = false;
                    console.log('disconnect', res.ErrorInfo);
                    break;
                case webim.CONNECTION_STATUS.RECONNECT:
                    this.state = true;
                    console.log('reconnect', res.ErrorInfo);
                    break;
                default:
                    this.state = false;
                    console.log('unknow', res.ErrorInfo);
                    break;
            }
        },

        // 监听新消息事件
        onMsgNotify(newMsgList) {
            console.log('onMsgNotify', newMsgList);
            for (let i in newMsgList) {
                let msg  = newMsgList[i];
                let list = msg.getElems();
                let id   = msg.getSession().id();
                let type = msg.getSession().type();

                let message = '';
                for (let item of list) {
                    switch (item.type) {
                        case 'TIMTextElem':
                            message = item.content.text;
                            break;
                        case 'TIMCustomElem':
                            message = item.content.data;
                            break;
                        default:
                            break;
                    }
                }

                if (!message) {
                   continue;
                }

                console.log("------message------", "id: ", id, "type: ", type, "message: ", message);

                this.messages.push({
                    'id':   id,
                    'type': type,
                    'text': message,
                });
            }
        },
    }
  }
</script>